<template>
  <div class="h-full bg-gray-50 p-4 overflow-y-auto">
    <h2 class="text-lg font-semibold mb-4">JSON Schema</h2>
    
    <div class="space-y-4">
      <el-button type="primary" size="small" @click="exportSchema">
        导出JSON Schema
      </el-button>
      
      <el-button size="small" @click="validateSchema">
        验证Schema
      </el-button>
      
      <el-button size="small" @click="copyToClipboard">
        复制到剪贴板
      </el-button>
    </div>

    <div class="mt-4">
      <el-alert
        v-if="validationResult"
        :type="validationResult.valid ? 'success' : 'error'"
        :title="validationResult.valid ? 'Schema验证通过' : 'Schema验证失败'"
        :description="validationResult.error || ''"
        show-icon
        class="mb-4"
      />
      
      <el-input
        v-model="schemaJson"
        type="textarea"
        :rows="12"
        placeholder="JSON Schema将在这里显示"
        readonly
        class="font-mono text-sm"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useDesignerStore } from '@/store'
import { exportToJSONSchema, validateFormSchema } from '@/utils/schemaValidator'

const { store } = useDesignerStore()
const validationResult = ref<{ valid: boolean; error?: string } | null>(null)

const schemaJson = computed(() => {
  try {
    const schema = exportToJSONSchema(store.currentForm)
    return JSON.stringify(schema, null, 2)
  } catch (error) {
    return JSON.stringify({ error: '生成Schema失败' }, null, 2)
  }
})

const exportSchema = () => {
  const data = schemaJson.value
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'form-schema.json'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

const validateSchema = () => {
  const isValid = validateFormSchema(store.currentForm)
  if (isValid) {
    validationResult.value = { valid: true }
    ElMessage.success('Schema验证通过')
  } else {
    validationResult.value = { 
      valid: false, 
      error: 'Schema格式不正确，请检查字段配置' 
    }
    ElMessage.error('Schema验证失败')
  }
}

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(schemaJson.value)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}
</script>